import React, { PureComponent, Fragment } from 'react'
import { Button, message } from 'antd'
import {ExportOutlined} from '@ant-design/icons'
import { connect } from 'dva'
import PateoTable from '@/common/PateoTable/PateoTable'
import * as G from '@/utils/common'
import { fingerprintFetch } from '@/utils/request'

@connect((state) => {
  return {
    common: state.common,
    loading: state.loading.models.common,
  }
})
export default class HistoryTab extends PureComponent {

  componentDidMount() {
    const { dispatch, deviceId } = this.props
    dispatch({
      type: 'common/pageGet',
      payload: { url: '/vehicle/findhistory', vin: deviceId, page: 0, size: 10 },
    })
  }

  exportHistory = () => {
    const { deviceId } = this.props
    const str = `${window.g.url}/vehicle/exportvehiclehistory/${deviceId}`
    const reqOption = {
      headers: { OptAuthorization: `bearer ${G.getToken()}` },
    }
    fingerprintFetch(str, reqOption)
      .then(response => {
        if (response.status === 200) {
          return response.blob()
        } else {
          throw response
        }
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `${deviceId}-${new Date().getTime()}.xls`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
      })
      .catch(() => message.error('导出失败，请稍后在试!'))
  }

  render() {
    const {
      common: { data: { list, pagination } }, loading, dispatch,
      deviceId,
    } = this.props
    const columns = [
      {
        width: '20%',
        title: '操作',
        dataIndex: 'operation',
      }, {
        width: '40%',
        title: '描述',
        dataIndex: 'description',
      }, {
        width: '15%',
        title: '操作人',
        dataIndex: 'createBy',
      }, {
        width: '15%',
        title: '操作时间',
        dataIndex: 'createDate',
      },
    ]

    const tableProps = {
      rowKey: 'sid',
      columns,
      dataSource: list,
      size: 'small',
      loading,
      pagination: G.paginationProps(pagination),
      scroll: { x: true }
    }
    return (
      <Fragment>
        <Button
          icon={<ExportOutlined />}
          onClick={this.exportHistory}
          style={{ marginBottom: 16 }}
        >
          导出
        </Button>
        <PateoTable
          dispatch={dispatch}
          tableProps={tableProps}
          fetchUrl='common/pageGet'
          parameterUrl='/vehicle/findhistory'
          formValues={{ vin: deviceId }}
        />
      </Fragment>
    )
  }
}
